import { globalShortcut, app, BrowserWindow } from 'electron'
import { EventEmitter } from 'events'

export interface ShortcutAction {
  id: string
  accelerator: string
  description: string
  handler: () => void
  global?: boolean
}

export class ShortcutService extends EventEmitter {
  private shortcuts: Map<string, ShortcutAction> = new Map()
  private mainWindow: BrowserWindow | null = null
  private isEnabled: boolean = true

  constructor(mainWindow: BrowserWindow) {
    super()
    this.mainWindow = mainWindow
    this.registerDefaultShortcuts()
  }

  /**
   * Register default shortcuts
   */
  private registerDefaultShortcuts(): void {
    // File operations
    this.register('file:new', 'CmdOrCtrl+N', '新建文件', () => {
      this.emit('newFile')
    })

    this.register('file:open', 'CmdOrCtrl+O', '打开文件', () => {
      this.emit('openFile')
    })

    this.register('file:save', 'CmdOrCtrl+S', '保存文件', () => {
      this.emit('saveFile')
    })

    this.register('file:save-as', 'CmdOrCtrl+Shift+S', '另存为', () => {
      this.emit('saveFileAs')
    })

    // Editor operations
    this.register('editor:undo', 'CmdOrCtrl+Z', '撤销', () => {
      this.mainWindow?.webContents.send('editor:undo')
    })

    this.register('editor:redo', 'CmdOrCtrl+Y', '重做', () => {
      this.mainWindow?.webContents.send('editor:redo')
    })

    this.register('editor:find', 'CmdOrCtrl+F', '查找', () => {
      this.mainWindow?.webContents.send('editor:find')
    })

    this.register('editor:replace', 'CmdOrCtrl+H', '替换', () => {
      this.mainWindow?.webContents.send('editor:replace')
    })

    // AI operations
    this.register('ai:polish', 'CmdOrCtrl+Shift+P', '润色选中文本', () => {
      this.mainWindow?.webContents.send('ai:polish')
    })

    this.register('ai:continue', 'CmdOrCtrl+J', '智能续写', () => {
      this.mainWindow?.webContents.send('ai:continue')
    })

    this.register('ai:translate', 'CmdOrCtrl+Shift+T', '翻译选中文本', () => {
      this.mainWindow?.webContents.send('ai:translate')
    })

    // View operations
    this.register('view:toggle-sidebar', 'CmdOrCtrl+B', '切换侧边栏', () => {
      this.mainWindow?.webContents.send('view:toggleSidebar')
    })

    this.register('view:toggle-dark-mode', 'CmdOrCtrl+Shift+D', '切换深色模式', () => {
      this.mainWindow?.webContents.send('view:toggleDarkMode')
    })

    this.register('view:focus-mode', 'CmdOrCtrl+Shift+F', '专注模式', () => {
      this.mainWindow?.webContents.send('view:focusMode')
    })

    this.register('view:typewriter-mode', 'CmdOrCtrl+Shift+T', '打字机模式', () => {
      this.mainWindow?.webContents.send('view:typewriterMode')
    })

    // Window operations
    this.register('window:minimize', 'CmdOrCtrl+M', '最小化窗口', () => {
      this.mainWindow?.minimize()
    })

    this.register('window:toggle-fullscreen', 'F11', '切换全屏', () => {
      if (this.mainWindow?.isFullScreen()) {
        this.mainWindow.setFullScreen(false)
      } else {
        this.mainWindow?.setFullScreen(true)
      }
    })

    this.register('window:devtools', 'F12', '开发者工具', () => {
      this.mainWindow?.webContents.toggleDevTools()
    })

    // Global shortcuts (work when app is not focused)
    this.registerGlobal('global:new-note', 'CmdOrCtrl+Shift+N', '快速新建笔记', () => {
      this.emit('globalNewNote')
    })

    this.registerGlobal('global:quick-open', 'CmdOrCtrl+Shift+O', '快速打开', () => {
      this.emit('globalQuickOpen')
    })
  }

  /**
   * Register a local shortcut (only works when app is focused)
   */
  public register(id: string, accelerator: string, description: string, handler: () => void): boolean {
    try {
      if (this.shortcuts.has(id)) {
        this.unregister(id)
      }

      const success = this.mainWindow?.webContents.on('before-input-event', (event, input) => {
        if (!this.isEnabled) return

        const key = this.formatAccelerator(input)
        if (key === accelerator) {
          event.preventDefault()
          handler()
        }
      })

      if (success) {
        this.shortcuts.set(id, {
          id,
          accelerator,
          description,
          handler,
          global: false
        })
        console.log(`Registered shortcut: ${id} (${accelerator})`)
        return true
      }

      return false
    } catch (error) {
      console.error(`Failed to register shortcut ${id}:`, error)
      return false
    }
  }

  /**
   * Register a global shortcut (works system-wide)
   */
  public registerGlobal(id: string, accelerator: string, description: string, handler: () => void): boolean {
    try {
      if (this.shortcuts.has(id)) {
        this.unregister(id)
      }

      const success = globalShortcut.register(accelerator, () => {
        if (this.isEnabled) {
          handler()
        }
      })

      if (success) {
        this.shortcuts.set(id, {
          id,
          accelerator,
          description,
          handler,
          global: true
        })
        console.log(`Registered global shortcut: ${id} (${accelerator})`)
        return true
      }

      return false
    } catch (error) {
      console.error(`Failed to register global shortcut ${id}:`, error)
      return false
    }
  }

  /**
   * Unregister a shortcut
   */
  public unregister(id: string): boolean {
    try {
      const shortcut = this.shortcuts.get(id)
      if (!shortcut) return false

      if (shortcut.global) {
        globalShortcut.unregister(shortcut.accelerator)
      }

      this.shortcuts.delete(id)
      console.log(`Unregistered shortcut: ${id}`)
      return true
    } catch (error) {
      console.error(`Failed to unregister shortcut ${id}:`, error)
      return false
    }
  }

  /**
   * Get all registered shortcuts
   */
  public getShortcuts(): ShortcutAction[] {
    return Array.from(this.shortcuts.values())
  }

  /**
   * Get shortcut by ID
   */
  public getShortcut(id: string): ShortcutAction | undefined {
    return this.shortcuts.get(id)
  }

  /**
   * Enable/disable all shortcuts
   */
  public setEnabled(enabled: boolean): void {
    this.isEnabled = enabled
    console.log(`Shortcuts ${enabled ? 'enabled' : 'disabled'}`)
  }

  /**
   * Check if shortcuts are enabled
   */
  public isShortcutEnabled(): boolean {
    return this.isEnabled
  }

  /**
   * Format keyboard input to accelerator string
   */
  private formatAccelerator(input: any): string {
    const parts: string[] = []

    if (input.control) parts.push('Ctrl')
    if (input.meta) parts.push('Cmd')
    if (input.alt) parts.push('Alt')
    if (input.shift) parts.push('Shift')

    if (input.key && input.key !== 'Meta' && input.key !== 'Control' &&
        input.key !== 'Alt' && input.key !== 'Shift') {
      parts.push(input.key.toUpperCase())
    }

    return parts.join('+')
  }

  /**
   * Export shortcuts configuration
   */
  public exportConfig(): Record<string, string> {
    const config: Record<string, string> = {}
    this.shortcuts.forEach((shortcut, id) => {
      config[id] = shortcut.accelerator
    })
    return config
  }

  /**
   * Import shortcuts configuration
   */
  public importConfig(config: Record<string, string>): void {
    Object.entries(config).forEach(([id, accelerator]) => {
      const shortcut = this.shortcuts.get(id)
      if (shortcut) {
        this.unregister(id)
        if (shortcut.global) {
          this.registerGlobal(id, accelerator, shortcut.description, shortcut.handler)
        } else {
          this.register(id, accelerator, shortcut.description, shortcut.handler)
        }
      }
    })
  }

  /**
   * Cleanup all shortcuts
   */
  public dispose(): void {
    // Unregister all global shortcuts
    this.shortcuts.forEach((shortcut) => {
      if (shortcut.global) {
        globalShortcut.unregister(shortcut.accelerator)
      }
    })

    this.shortcuts.clear()
    this.removeAllListeners()
    console.log('All shortcuts unregistered')
  }
}